package de.gameduell.net.src.encryption {

	public class Shuffle implements IEncryption {

		private static var TAB:String = "\t";

		public function Shuffle() {
		}

		/**
		 * 
		 */
		public function encrypt(originalString:String):String {
			if ((originalString.length % 2) != 0) {
				originalString = originalString + TAB;
			}
			var shuffledString:String = "";
			var i:Number;
			var i2:Number;
			for (i = 0;i < originalString.length; i++) {
				i2 = int(i / 2);
				if ((i % 2) == 0) {
					shuffledString = shuffledString + originalString.charAt(i2);
				} else {
					shuffledString = shuffledString + originalString.charAt((originalString.length - 1) - i2);
				}
			}
			return shuffledString;
		}

		/**
		 * 
		 */
		public function decrypt(originalString:String):String {
			var deshuffledString:String = "";
			var i:Number;

			var length:Number = originalString.length;
			var deshuffled:Array = new Array(length);
			var pos:Number = 0;

			for (i = 1;i < length; i += 2) {
				deshuffled[pos] = originalString.charAt(i - 1);
				pos++;	
			}
		
			for (i = length;i > 0; i -= 2) {	
				deshuffled[pos] = originalString.charAt(i - 1);
				pos++;				
			}
			deshuffledString = deshuffled.join("");
			if (deshuffledString.charAt(deshuffledString.length - 1) == TAB) {
				deshuffledString = deshuffledString.substring(0, deshuffledString.length - 1);
			}
			return deshuffledString;
		}	
	}
}
